<!--
  功能：院校渠道
  作者：licy
  邮箱：licy@briup.com
  时间：2020年11月30日 16:03:33
  版本：v1.0
  修改记录：
  修改内容：
  修改人员：
  修改时间：
-->
<template>
  <div class="channel_list">
    <div class="title">
      渠道信息
      <div class="btn_box">
        <el-button size="mini" type="primary" @click="toAddHandler"
          >新增</el-button
        >
      </div>
    </div>
    <!-- 按钮 -->

    <!--/ 按钮 -->
    <!-- 表格 -->
    <el-table
      size="small"
      v-loading="loading"
      :data="channelData.list"
      highlight-current-row
      row-key="id"
      border
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      @current-change="channelRowClickHandler"
    >
      <el-table-column prop="name" label="渠道名称"> </el-table-column>
      <el-table-column width="120" label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="toEdit(scope.row)"
            >修改</el-button
          >
          <el-button type="text" size="mini" @click="delHandler(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- / 表格 -->
    <!-- 分页 -->
    <div class="page">
        <el-pagination background 
          layout="prev, pager, next,sizes" 
          small
          :total="channelData.total" 
          :page-size="channelData.pageSize" 
          :current-page="channelData.page"
          :page-sizes="[10, 15, 20,25,50,100]"
          @size-change="handleSizeChange"
          @current-change="currentChangeHandler">
        </el-pagination>
    </div>
    <!-- /分页 -->
    <!-- 抽屉 -->
    <Briupdrawer
      :drawer-visible="visible"
      :title="title"
      width="40%"
      @on-change-visible="handlerVisibleChange"
    >
      <div slot="content">
        <el-form
          size="small"
          ref="channel_form"
          :model="form"
          :rules="rules"
          label-width="80px"
        >
          <el-form-item label="渠道类型" prop="type">
            <el-select v-model="form.type" style="width: 100%">
              <el-option label="学校" value="学校"></el-option>
              <el-option label="学院" value="学院"></el-option>
              <el-option label="其他" value="其他"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="渠道名称" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="上级渠道" prop="parentId">
            <el-cascader filterable
              style="width: 100%"
              v-model="form.parentId"
              clearable
              :options="channelData.list"
              placeholder="一级渠道"
              :props="{
                checkStrictly: true,
                children: 'children',
                label: 'name',
                value: 'id',
                emitPath: false,
              }"
            ></el-cascader>
          </el-form-item>

          <!-- <el-form-item label="地址" prop="pca">
            <el-cascader filterable v-model="form.pca" :options="pca"  :props="{label:'name',value:'name'}"  @change="pcaChange" ></el-cascader>
          </el-form-item>
          <el-form-item label="详细地址" prop="address">
             <el-input v-model="form.address"></el-input>
          </el-form-item>
           -->
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="visible = false">取 消</el-button>
        <el-button type="primary" size="small" @click="submitHandler"
          >确 定</el-button
        >
      </span>
    </Briupdrawer>
    <!-- 抽屉结束 -->
    <!-- -----------------------------------渠道负责人---------------------------------------- -->
    <div v-if="channel">
      <!-- 渠道负责人 -->
      <div class="title">
        {{ channel.name }} - 渠道负责人
        <div class="btn_box">
          <el-button size="mini" type="primary" @click="toAddClientHandler"
            >录入</el-button
          >
        </div>
      </div>
      <!-- 渠道负责人表格 -->
      <el-table size="mini" :data="clientData.list">
        <el-table-column
          label="序号"
          type="index"
          :index="1"
          align="center"
        ></el-table-column>
        <el-table-column
          label="姓名"
          prop="realname"
          align="center"
          width="80"
        ></el-table-column>
        <el-table-column
          label="性别"
          prop="gender"
          align="center"
          width="60"
        ></el-table-column>
        <el-table-column
          label="职务"
          prop="job"
          align="center"
          width="180"
        ></el-table-column>
        <el-table-column
          label="联系方式"
          prop="telephone"
          align="center"
          width="120"
        ></el-table-column>
        <el-table-column
          label="email"
          prop="email"
          align="center"
          width="160"
        ></el-table-column>
        <el-table-column
          label="备注"
          prop="comment"
          align="center"
        ></el-table-column>
        <el-table-column width="120" label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="toEditClient(scope.row)"
              >修改</el-button
            >
            <el-button
              type="text"
              size="mini"
              @click="delClientHandler(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- /渠道负责人 -->
    </div>
    <!-- 抽屉 -->
    <Briupdrawer
      :drawer-visible="visible_client"
      title="渠道负责人"
      width="40%"
      @on-change-visible="handlerVisibleClientChange"
    >
      <div slot="content">
        <el-form
          size="small"
          ref="client_form"
          :model="form_client"
          :rules="rules_client"
          label-width="60px"
        >
          <el-form-item label="渠道" v-if="channel">
            {{ channel.name }}
          </el-form-item>
          <el-form-item label="姓名" prop="realname">
            <el-input v-model="form_client.realname" />
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="form_client.gender">
              <el-radio label="男">男</el-radio>
              <el-radio label="女">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="职务" prop="job">
            <el-input v-model="form_client.job" />
          </el-form-item>
          <el-form-item label="手机" prop="telephone">
            <el-input v-model="form_client.telephone" />
          </el-form-item>
          <el-form-item label="email" prop="email">
            <el-input v-model="form_client.email" />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="visible_client = false"
          >取 消</el-button
        >
        <el-button type="primary" size="small" @click="submitClientHandler"
          >确 定</el-button
        >
      </span>
    </Briupdrawer>
    <!-- 抽屉结束 -->
  </div>
</template>

<script>
import { get, post } from "@/utils/request";
import _ from "lodash";
import pca from "@/assets/pca.json";
import qs from "qs";
export default {
  // 组件名称
  name: "demo",
  // 组件参数 接收来自父组件的数据
  props: {},
  // 组件状态值
  data() {
    return {
      loading: false,
      channelData: {list:[]},
      channel: null,
      param: {
        page: 1,
        pageSize: 15,
      },
      form: {},
      title: "新增",
      visible: false,
      pca,
      rules: {
        name: [{ required: true, message: "请输入渠道名称", trigger: "blur" }],
        type: [{ required: true, message: "请选择类型", trigger: "change" }],
      },
      clientData: { list: [] },
      // 负责人
      param_client: {
        page: 1,
        pageSize: 100,
      },
      visible_client: false,
      form_client: {
        gender: "男",
      },
      rules_client: {
        realname: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        gender: [{ required: true, message: "请输入性别", trigger: "blur" }],
        job: [{ required: true, message: "请输入职务", trigger: "blur" }],
        telephone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
        ],
      },
    };
  },
  // 计算属性
  computed: {},
  // 侦听器
  watch: {
    param_client: {
      handler: function () {
        // 加载渠道负责人
        this.loadClient();
      },
      deep: true,
    },
  },
  // 组件方法
  methods: {
    // 去编辑
    toEditClient(row) {
      this.form_client = _.clone(row);
      this.visible_client = true;
    },
    // 删除
    delClientHandler(row) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let url = "/client/deleteById";
        get(url, { id: row.id }).then((response) => {
          this.$message({ type: "success", message: response.message });
          this.loadClient();
        });
      });
    },

    // 保存区域负责人
    submitClientHandler() {
      this.$refs["client_form"].validate((valid) => {
        if (valid) {
          const url = "/client/saveOrUpdate";
          post(url, this.form_client).then((response) => {
            this.visible_client = false;
            this.$message({ message: response.message, type: "success" });
            this.loadClient();
          });
        } else {
          return false;
        }
      });
    },
    // 去添加区域负责人
    toAddClientHandler() {
      if (!this.channel) {
        this.$message({ type: "danger", message: "您还没有选择渠道" });
        return false;
      }
      this.form_client = { gender: "男" };
      this.form_client.channelId = this.channel.id;
      this.visible_client = true;
    },
    // 点击渠道的事件处理函数
    channelRowClickHandler(row) {
      this.channel = row;
      let tree = [_.clone(row)];
      // 数组扁平化
      let ids = [];
      function flat(arr) {
        arr.forEach((item) => {
          ids.push(item);
          item.children && item.children.length > 0 ? flat(item.children) : "";
        });
      }
      flat(tree);
      this.param_client = {
        ...this.param_client,
        channelIds: ids.map((item) => item.id),
      };
    },
    // 省市区变化处理函数
    pcaChange(val) {
      this.form.province = val[0];
      this.form.city = val[1];
      this.form.area = val[2];
    },
    // 删除
    delHandler(row) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let url = "/channel/deleteById";
        get(url, { id: row.id }).then((response) => {
          this.$message({ type: "success", message: response.message });
          this.loadChannel();
        });
      });
    },
    // 提交处理函数
    submitHandler() {
      this.$refs["channel_form"].validate((valid) => {
        if (valid) {
          const url = "/channel/saveOrUpdate";
          post(url, this.form).then((response) => {
            this.visible = false;
            this.$message({ message: response.message, type: "success" });
            this.loadChannel();
          });
        } else {
          return false;
        }
      });
    },
    // 去编辑
    toEdit(row) {
      this.form = _.clone(row);
      this.form.pca = [this.form.province, this.form.city, this.form.area];
      this.visible = true;
    },
    // 去添加
    toAddHandler() {
      this.form = {};
      this.visible = true;
    },
    // 加载渠道负责人信息
    loadClient() {
      let url = "/client/pageQuery";
      get(
        url + "?" + qs.stringify(this.param_client, { arrayFormat: "repeat" })
      ).then((response) => {
        this.clientData = response.data;
      });
    },
    // 加载渠道信息
    loadChannel() {
      this.loading = true;
      let url = "/channel/queryTree";
      get(url,this.param).then((response) => {
        this.channelData = response.data;
        this.loading = false;
      });
    },
    //处理visible变化的钩子函数,解决抽屉无法收缩的bug
    handlerVisibleChange(val) {
      this.visible = val;
      this.$refs["channel_form"].clearValidate();
    },
    handlerVisibleClientChange(val) {
      this.visible_client = val;
    },
     // 当前页发生改变
    currentChangeHandler(page){
      this.param.page = page;
      this.loadChannel();
    },
     // 处理分页大小变化的函数
    handleSizeChange(pageSize){
      // 当前页为第一页
      this.page = 1;
      // 页面大小为用户选择的页面
      this.param.pageSize = pageSize;
      this.loadChannel();
    }
  },
  // 以下是生命周期钩子
  /**
   * 组件实例创建完成，属性已绑定，但DOM还未生成，$ el属性还不存在
   */
  created() {
    // 加载渠道信息
    this.loadChannel();
    // 加载渠道负责人信息
    this.loadClient();
  },
  /**
   * el 被新创建的 vm.$ el 替换，并挂载到实例上去之后调用该钩子。
   * 如果 root 实例挂载了一个文档内元素，当 mounted 被调用时 vm.$ el 也在文档内。
   */
  mounted() {},
  /**
   * 实例销毁之前调用。在这一步，实例仍然完全可用。
   */
  beforeDestroy() {},
  /**
   * Vue 实例销毁后调用。调用后，Vue 实例指示的所有东西都会解绑定，
   * 所有的事件监听器会被移除，所有的子实例也会被销毁。
   */
  destroyed() {},
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<!--使用了scoped属性之后，父组件的style样式将不会渗透到子组件中，-->
<!--然而子组件的根节点元素会同时被设置了scoped的父css样式和设置了scoped的子css样式影响，-->
<!--这么设计的目的是父组件可以对子组件根元素进行布局。-->
<style scoped lang="scss">
.channel_list {
  color: #999;
  .title {
    height: 3em;
    line-height: 3em;
    background-color: #f4f4f4;
    padding: 0 1em;
    margin: 0.5em 0;
    font-weight: bold;
    font-size: 12px;
    border-radius: 5px;

    .btn_box {
      float: right;
    }
  }
}
</style>

